import time
import keyboard

from key_presser import CDDdriver
from screenshot_get_position import ScreenshotGetPosition

import matplotlib.pyplot as plt


class RectangleSplitter:
    def __init__(self, rectangle):
        """
        初始化 RectangleSplitter 类。
        :param rectangle: 表示矩形的元组，格式为 ((x1, y1), (x2, y2))，其中 (x1, y1) 是左上角点，(x2, y2) 是右下角点。
        """
        self.rectangle = rectangle

    def split_horizontally(self, num_splits=8):
        """
        将矩形横向平分为指定数量的矩形，并返回这些矩形的中心点。
        :param num_splits: 要划分的数量，默认为 8。
        :return: 存储划分后矩形中心点的列表，每个元素是一个 (x, y) 元组。
        """
        (x1, y1), (x2, y2) = self.rectangle
        dx = (x2 - x1) / num_splits  # 计算每个小矩形的宽度
        centers = []
        for i in range(num_splits):
            new_x1 = x1 + i * dx
            new_x2 = x1 + (i + 1) * dx
            center_x = (new_x1 + new_x2) / 2
            center_y = (y1 + y2) / 2  # 计算 y 方向的中心，y 方向不变
            centers.append((center_x, center_y))
        return centers

    def find_small_rectangle(self, point):
        """
        判断输入的点位于哪个小矩形中。
        :param point: 输入的点坐标，格式为 (x, y)。
        :return: 点所在的小矩形的索引（从 1 开始），如果不在任何小矩形中返回 -1。
        """
        (x1, y1), (x2, y2) = self.rectangle
        dx = (x2 - x1) / len(self.split_horizontally())  # 获取每个小矩形的宽度
        x, y = point
        if x < x1 or x > x2 or y < y1 or y > y2:
            return -1
        index = int((x - x1) // dx)
        return index + 1

    def get_small_rectangle_corners(self, index):
        """
        根据输入的索引（从 1 开始）返回对应的小矩形的角点。
        :param index: 小矩形的索引，从 1 开始。
        :return: 对应的小矩形的角点，格式为 ((x1, y1), (x2, y2))，如果索引无效返回 None。
        """
        (x1, y1), (x2, y2) = self.rectangle
        dx = (x2 - x1) / len(self.split_horizontally())  # 获取每个小矩形的宽度
        if index < 1 or index > len(self.split_horizontally()):
            return None
        actual_index = index - 1  # 转换为从 0 开始的索引
        new_x1 = x1 + actual_index * dx
        new_x2 = x1 + (actual_index + 1) * dx
        return ((new_x1, y1), (new_x2, y2))


import pyautogui
import cv2
import numpy as np


class ImageCropper:
    def __init__(self, rectangle):
        """
        初始化 ImageCropper 类。
        :param rectangle: 输入的矩形范围，格式为 ((x1, y1), (x2, y2))，其中 (x1, y1) 是左上角点，(x2, y2) 是右下角点。
        """
        self.rectangle = rectangle

    def capture_and_crop(self):
        """
        该方法用于截取全屏，然后根据输入的矩形范围裁剪图像。
        :return: 裁剪后的图像
        """
        # 截取全屏
        screenshot = pyautogui.screenshot()
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        (x1, y1), (x2, y2) = self.rectangle
        # 裁剪图像
        cropped_image = screenshot[y1:y2, x1:x2]
        return cropped_image

    def get_cropped_image_size(self):
        """
        该方法用于计算裁剪后图像的尺寸。
        :return: 裁剪后图像的尺寸，格式为 (x2, y2)，假设 (x1, y1) 为 (0, 0)
        """
        (x1, y1), (x2, y2) = self.rectangle
        width = x2 - x1
        height = y2 - y1
        return width, height

    def compare_brightness(self, image1, image2, threshold=10):
        """
        该方法用于对比两张图像的亮度差异点，并返回亮度差异点的统计中心。
        :param image1: 第一张图像
        :param image2: 第二张图像
        :param threshold: 亮度差异的阈值，默认为 10
        :return: 亮度差异点的统计中心，格式为 (x, y)
        """
        if image1.shape != image2.shape:
            raise ValueError("The two images must have the same shape.")
        gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
        gray_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
        diff = cv2.absdiff(gray_image1, gray_image2)
        _, thresh = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        total_x = 0
        total_y = 0
        num_points = 0
        for contour in contours:
            for point in contour:
                x, y = point[0]
                total_x += x
                total_y += y
                num_points += 1
        if num_points == 0:
            return None
        center_x = int(total_x / num_points)
        center_y = int(total_y / num_points)
        return [center_x, center_y]


import pyttsx3


def on_press(event):
    if event.name == 'f9':
        global loop_flag
        loop_flag = False
        print("F9 pressed, stopping loop.")
    elif event.name == 'f8':
        global stop_flag
        stop_flag = not stop_flag
        print(f"F8 pressed {stop_flag}")

        engine = pyttsx3.init()
        engine.setProperty('volume', 1.0)  # 设置为50%音量
        # 播放蜂鸣声（频率1000Hz，持续1秒）
        if stop_flag:
            engine.say("QTE暂停")
        else:
            engine.say("QTE启动")
        engine.runAndWait()


class CWuShi:
    def __init__(self):
        # 获取关注矩形
        pos_ins = ScreenshotGetPosition(1)
        rectangles = pos_ins.GetPoints()
        print(rectangles)
        self.__rectangle = rectangles[0]
        self.__dd = CDDdriver()

    def imshow(self, img1, img2):
        # 创建子图布局
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

        # 显示图片并隐藏坐标轴
        ax1.imshow(img1)
        ax1.axis('off')
        ax1.set_title('Screenshot 1')

        ax2.imshow(img2)
        ax2.axis('off')
        ax2.set_title('Screenshot 2')

        plt.tight_layout()
        plt.show()

    def do_qte(self, num):
        self.__dd.press(num)

    def run(self):
        # 图像裁剪
        image_cropper = ImageCropper(self.__rectangle)
        rectangle_size = [abs(self.__rectangle[0][0] - self.__rectangle[1][0]),
                          abs(self.__rectangle[0][1] - self.__rectangle[1][1])]
        # 截图+裁剪
        result_image1 = image_cropper.capture_and_crop()
        # 截图间隔
        time.sleep(50e-3)
        # 截图2+裁剪
        result_image2 = image_cropper.capture_and_crop()

        # 图像比对
        point = image_cropper.compare_brightness(result_image1, result_image2, 20)
        if point is not None:
            # self.imshow(result_image1, result_image2)
            proportion = [0, 0]
            proportion[0] = 1 + int(4 * float(point[0]) / float(rectangle_size[0]))
            proportion[1] = int(1 * float(point[1]) / float(rectangle_size[1]))
            self.do_qte(proportion[0])


if __name__ == "__main__":
    # 循环模块
    loop_time = 10  # 10s一次
    loop_flag = True
    stop_flag = True
    loop_cnt = 0

    # 功能模块初始化
    solution = CWuShi()

    # 设置键盘监听
    keyboard.on_press(on_press)

    while loop_flag:
        if loop_cnt == 0:
            solution.run()
        if not stop_flag:
            loop_cnt = (loop_cnt + 1) % loop_time
        time.sleep(50 * 1e-3)
